package com.seele.tigerwallet.ui.views;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.ui.adapter.AddAssetsAdapter;
import com.seele.tigerwallet.ui.callback.BaseListener;
import com.seele.tigerwallet.ui.callback.OnSelectListener;
import com.seele.tigerwallet.ui.utils.DividerItemDecoration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Call;

import static com.chad.library.adapter.base.BaseQuickAdapter.RequestLoadMoreListener;

public class AddAssetsRecyclerView extends RecyclerView implements RequestLoadMoreListener {
    private AddAssetsAdapter mAddAssetsAdapter;
    private List<AssetsModel> mBundleList;//传值
    private int num = 20;
    private List<Integer> list = new ArrayList<>();

    private OnSelectListener onSelectListener;

    private Map<Integer, AssetsModel> modelMap = new ConcurrentHashMap<>();

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    public void setListener(BaseListener listener) {
        if (listener instanceof OnSelectListener) {
            this.onSelectListener = (OnSelectListener) listener;
        }

    }

    public void notifyDataSetChanged() {
        if (null != mAddAssetsAdapter) {
            mAddAssetsAdapter.notifyDataSetChanged();
        }
    }

    public AddAssetsRecyclerView(Context context) {
        this(context, null);
    }

    public AddAssetsRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddAssetsRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);


    }


    /**
     * 设置
     */
    public void setBundleList(List<AssetsModel> bundleList, boolean isLoad) {
        this.mBundleList = bundleList;
        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }

        if (null!=modelMap){
            modelMap.clear();
        }
        if (null != bundleList && bundleList.size() > 0) {
            for (AssetsModel assetsModel : bundleList) {
                addAssetsModel(assetsModel);
            }

        }
        if (isLoad) {
            //查询本地数据
            new Thread(new Runnable() {
                @Override
                public void run() {


                }
            }).start();

            initData(1, true);
        }


    }

    public void addAssetsModel(AssetsModel assetsModel) {
        if (null != assetsModel) {
            if (!modelMap.containsKey(assetsModel.id)) {
                modelMap.put(assetsModel.id, assetsModel);
            }
        }
    }


    /**
     * @param context
     */
    private void initView(Context context) {
        if (null == context) {
            return;
        }
        setLayoutManager(new LinearLayoutManager(context));
        addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.HORIZONTAL, (int) getResources().getDimension(R.dimen.dp_1), getResources().getColor(R.color.color_F9F9F9))); //设置item的分割线

        if (null == mAddAssetsAdapter) {
            mAddAssetsAdapter = new AddAssetsAdapter(R.layout.item_add_assets);
        }
//        mAddAssetsAdapter.setOnLoadMoreListener(this, this);
//        mAddAssetsAdapter.setEnableLoadMore(true);
        setAdapter(mAddAssetsAdapter);
        mAddAssetsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AssetsModel item = null;
                if (null != mAddAssetsAdapter) {
                    item = mAddAssetsAdapter.getData().get(position);
                }
                switch (view.getId()) {
                    case R.id.check_ll:
                        handlerSelect(item);
                        break;
                }
            }
        });

//        initData(0, true);
    }

    /**
     * 处理选择的资产
     *
     * @param item
     */
    private void handlerSelect(AssetsModel item) {
        if (null == item) {
            return;
        }
        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }


        boolean isOpen = item.isOpen;
        if (isOpen) {
            item.isOpen = false;
        } else {
            item.isOpen = true;
        }
        mAddAssetsAdapter.notifyDataSetChanged();
        clear();
        for (AssetsModel assetsModel : mBundleList) {
            list.add(assetsModel.id);
        }
        if (item.isOpen) {
            if (!list.contains(item.id)) {
                mBundleList.add(item);
            }
        } else {
            if (list.contains(item.id)) {
                for (int i = mBundleList.size() - 1; i >= 0; i--) {
                    if (mBundleList.get(i).id == item.id) {
                        mBundleList.remove(i);
                    }
                }
            }
        }

        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }
    }

    private void initData(int id, final boolean isRefresh) {
        APIModule
                .getApi()
                .symbollistBylevel(id, num)
                .enqueue(new APIListCallBack<AssetsModel>() {

                    @Override
                    protected void onResponse(List<AssetsModel> response) {
                        try {

                            handleData(response, isRefresh);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        if (!isRefresh) {
                            mAddAssetsAdapter.loadMoreFail();
                        }

                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        if (!isRefresh) {
                            mAddAssetsAdapter.loadMoreFail();
                        }
                    }


                });


    }

    /**
     * 数据处理
     *
     * @param response
     * @param isRefresh
     */
    private void handleData(List<AssetsModel> response, boolean isRefresh) {
        int size = response == null ? 0 : response.size();
        if (size > 0) {
            clear();
            if (null == mBundleList) {
                mBundleList = new ArrayList<>();
            }
            for (AssetsModel assetsModel : response) {
                assetsModel.candisable = 1;
                if (!modelMap.containsKey(assetsModel.id)) {
                    modelMap.put(assetsModel.id, assetsModel);
                }
            }
            Collection<AssetsModel> values = modelMap.values();

            List<AssetsModel> assetsModels = new ArrayList<AssetsModel>(values);

            //自定义排序1
            Collections.sort(assetsModels, new Comparator<AssetsModel>() {
                @Override
                public int compare(AssetsModel t1, AssetsModel t2) {
                    if (t1.level > t2.level) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            });

            setAdapter(mAddAssetsAdapter);
            mAddAssetsAdapter.setNewData(assetsModels);

        } else {
            if (isRefresh) {
                setAdapter(mAddAssetsAdapter);
                mAddAssetsAdapter.setNewData(response);
            } else {
                mAddAssetsAdapter.loadMoreEnd(isRefresh);
            }
        }
    }


    private void clear() {
        if (list.size() > 0) {
            list.clear();
        }

    }

    @Override
    public void onLoadMoreRequested() {//下拉加载
        if (null != mAddAssetsAdapter) {
            List<AssetsModel> assetsModels = mAddAssetsAdapter.getData();
            int size = assetsModels == null ? 0 : assetsModels.size();
            if (size > 0) {
                int id = assetsModels.get(size - 1).id + 1;
                initData(id, false);
            }
        }


    }


}
